import dayjs from 'dayjs'
import md5 from "blueimp-md5";
import store from '@/store/index'
import CryptoJS from "crypto-js";
import jsrsasign from 'jsrsasign'
import {
	Base64
} from 'js-base64';
import {
	privateKey
} from "./private.key";
// 根据时间排序，property是你需要排序传入的key,bol为true时是升序，false为降序
export const dateSort = (property, bol) => {
	return function(a, b) {
		var value1 = a[property];
		var value2 = b[property];
		if (bol) {
			// 升序
			return Date.parse(value1) - Date.parse(value2);
		} else {
			// 降序
			return Date.parse(value2) - Date.parse(value1)
		}
	}
}

//前端分页处理
export const handlePagination = (params) => {
	let start = (params.currentPage - 1) * params.pageSize;
	if (start >= params.list.length) {
		start = 0;
	}
	let end = params.currentPage * params.pageSize;
	if (end >= params.list.length) {
		end = params.list.length;
	}
	return params.list.slice(start, end);
};
export const getSexByIdCard = (id) => {
	var sex;
	if (id.length == 15) {
		if (parseInt(id.charAt(14) / 2) * 2 != id.charAt(14)) {
			sex = "1";
		} else {
			sex = "2";
		}
	} else if (id.length == 18) {
		if (parseInt(id.charAt(16) / 2) * 2 != id.charAt(16)) {
			sex = "1";
		} else {
			sex = "2";
		}
	}
	return sex;
};

export const getAgeByIdCard = (identityCard) => {
	var len = (identityCard + "").length;
	if (len == 0) {
		return 0;
	} else {
		if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法
		{
			return 0;
		}
	}
	var strBirthday = "";
	if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
	{
		strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12,
			2);
	}
	if (len == 15) {
		strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard
			.substr(10,
				2);
	}
	//时间字符串里，必须是“/”
	var birthDate = new Date(strBirthday);
	var nowDateTime = new Date();
	var age = nowDateTime.getFullYear() - birthDate.getFullYear();
	//再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
	if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() &&
			nowDateTime
			.getDate() <
			birthDate.getDate())) {
		age--;
	}
	return age;
}

export const getBirthdayByIdCard = function(idCard) {
	var birthday = "";
	if (idCard != null && idCard != "") {
		if (idCard.length == 15) {
			birthday = "19" + idCard.substr(6, 6);
		} else if (idCard.length == 18) {
			birthday = idCard.substr(6, 8);
		}

		// birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
		birthday = birthday.replace(/(.{4})(.{2})/, "$1$2");
	}

	return birthday;
};


export const hideStr = (begin, end, data) => {
	if (!data) {
		return ""
	}
	let tempStr = '';
	const length = data.length;
	const beginStr = data.substr(0, begin);
	const endStr = data.substr(length - end, end);
	for (let i = 0; i < length - (begin + end); i++) {
		tempStr += '*';
	}
	tempStr = beginStr + tempStr + endStr
	return tempStr;
}
//姓名脱敏
export const hideStrForName = (name) => {
	if (!name) {
		return ""
	}
	name = name.trim()
	if (name.length == 1) {
		return hideStr(0, 0, name)
	} else if (name.length == 2) {
		return hideStr(0, 1, name)
	} else if (name.length > 2) {
		return hideStr(1, 1, name)
	} else {
		return name
	}
}
//手机号脱敏
export const hideStrForTel = (tel) => {
	if (!tel) {
		return ""
	}
	if (tel.length == 11) {
		return hideStr(3, 2, tel)
	} else {
		return tel
	}
}
//身份证脱敏
export const hideStrForIdCard = (idCard) => {
	if (!idCard) {
		return ""
	}
	if (idCard.length == 18 || idCard.length == 15) {
		// var str = hideStr(1, 14, idCard)
		// return hideStr(12, 1, str)
		return hideStr(3, 3, idCard)
	} else {
		return idCard
	}
}

//身份证脱敏(隐藏后4位)
export const hideStrForIdCardLast4Digt = (idCard) => {
	if (idCard) {
		if (idCard.length == 18 || idCard.length == 15) {
			// var str = hideStr(1, 14, idCard)
			// return hideStr(12, 1, str)
			return hideStr(14, 0, idCard)
		} else {
			return idCard
		}
	}

}


//获取星期中文
export const getWeekText = (week) => {
	let list = [{
		label: '日',
		value: '0',
	}, {
		label: '一',
		value: '1',
	}, {
		label: '二',
		value: '2',
	}, {
		label: '三',
		value: '3',
	}, {
		label: '四',
		value: '4',
	}, {
		label: '五',
		value: '5',
	}, {
		label: '六',
		value: '6',
	}]
	let item = list.find((t) => {
		return t.value == week;
	})
	return `${item.label}`

}
export const isAfternoon = () => {
	// console.log(moment().startOf('day').valueOf() + 12 * 60 * 60 * 1000 - (new Date()).valueOf())
	// 当天中午距离此刻的时间
	let timeDis = dayjs().startOf('day').valueOf() + 12 * 60 * 60 * 1000 - (new Date()).valueOf()
	if (timeDis < 0) {
		console.log('现在已经是下午')
	}
	return timeDis < 0
}

//object转string,用于签名计算
export function obj2str(args) {
	var keys = Object.keys(args)
	keys = keys.sort() //参数名ASCII码从小到大排序（字典序）；
	var newArgs = {}
	keys.forEach(function(key) {
		if (typeof(args[key]) == "number" && !args[key]) {
			newArgs[key] = args[key]
		}
		if (args[key] != "" && args[key] != 'undefined') { //如果参数的值为空不参与签名；
			newArgs[key] = args[key] //参数名区分大小写；
		}

	})
	var string = ''
	for (var k in newArgs) {
		string += '&' + k + '=' + newArgs[k]
	}
	string = string.substr(1)
	return string
}
export function paysignjs(jsonobj, paySecret) {
	var signstr = obj2str(jsonobj)
	signstr = signstr + '&paySecret=' + paySecret;
	// console.log("signstrkey:", signstr)
	var sign = md5(signstr); //验证调用返回或微信主动通知签名时，传送的sign参数不参与签名，将生成的签名与该sign值作校验。
	return sign.toUpperCase()
}
//生成随机订单号
export const getOrderNumber = (idCard) => {
	return store.state.deviceInfo.machineNumber + dayjs().valueOf();
};
//把数据处理成数组
export const objectToArray = (data) => {
	if (!data) {
		return []
	}
	if (Array.isArray(data)) {
		return data
	} else {
		return [data]
	}
};
//分组
export const groupBy=(array, key, resKey = "children")=> {
	if (!key) return array;
    var aMap = [];
    var aResult = [];
    for (var i = 0; i < array.length; i++) {
        var item = array[i];
        if (aMap.indexOf(item[key]) === -1) {
            var oItem = {};
            oItem[resKey] = [item];
            oItem[key] = item[key];
            aResult.push(oItem);
            aMap.push(item[key]);
        } else {
            var index = aMap.indexOf(item[key]);
            aResult[index][resKey].push(item);
        }
    }
    return aResult;
}
//获取url参数
export const getQueryString = (name) => {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}
//数组去重
export const unique = (arr, uniId) => {
	const res = new Map();
	return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}
//是否永居证（老版/新版外国人身份证）
export const isForeignerIdCard = (id) => {
	// 1 "验证通过!", 0 //校验不通过 // id为身份证号码

	// 新 增加新版永居证号码 以9开头再加受理区域
	var format =
		/^((([9](([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2])))\d{3}))(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
	var format15Foreign =
		/^[a-zA-Z]{3}[0-9]{4}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{2}$/;
	
	//号码规则校验
	if (!(format.test(id) || format15Foreign.test(id))) {
		return false;
		// return {
		// 	'status': 0,
		// 	'msg': '身份证号码不合规'
		// };
	}
	//区位码校验
	if (id.length == 18) {
		//出生年月日校验  前正则限制起始年份为1900;
		var year = id.substr(6, 4), //身份证年
			month = id.substr(10, 2), //身份证月
			date = id.substr(12, 2), //身份证日
			time = Date.parse(month + '-' + date + '-' + year), //身份证日期时间戳date
			now_time = Date.parse(new Date()), //当前时间戳
			dates = (new Date(year, month, 0)).getDate(); //身份证当月天数
		if (time > now_time || date > dates) {
			return false;
			// return {
			// 	'status': 0,
			// 	'msg': '出生日期不合规'
			// }
		}

		//校验码判断
		var c = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //系数
		var b = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); //校验码对照表
		var id_array = id.split("");
		var sum = 0;
		for (var k = 0; k < 17; k++) {
			sum += parseInt(id_array[k]) * parseInt(c[k]);
		}
		if (id_array[17].toUpperCase() != b[sum % 11].toUpperCase()) {
			return false;
			// return {
			// 	'status': 0,
			// 	'msg': '身份证校验码不合规'
			// }
			
		}
	}
	return true;
	// return {
	// 	'status': 1,
	// 	'msg': '校验通过'
	// }
}
//根据永居证获取出生日期
export const getBirthdayByForeignerIdCard = (idCard) => {
	if (idCard.length == 18) {
		return idCard.substr(6, 8);
	} else {
		return `19${idCard.substr(7, 6)}`
	}
}
//根据永居证获取年龄
export const getAgeByForeignerIdCard = (identityCard) => {
	var len = (identityCard + "").length;
	if (len == 0) {
		return 0;
	} else {
		if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法
		{
			return 0;
		}
	}
	var strBirthday = "";
	if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
	{
		strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12,
			2);
	}
	if (len == 15) {
		
		strBirthday = "19" + identityCard.substr(7, 2) + "/" + identityCard.substr(9, 2) + "/" + identityCard
			.substr(11,
				2);
	}
	//时间字符串里，必须是“/”
	var birthDate = new Date(strBirthday);
	var nowDateTime = new Date();
	var age = nowDateTime.getFullYear() - birthDate.getFullYear();
	//再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
	if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() &&
			nowDateTime
			.getDate() <
			birthDate.getDate())) {
		age--;
	}
	return age;
}

/**
 * 加密
 * @param {string} message 需要加密的字符串
 * @param {string} key 密钥
 * @return {string} 加密字符串
 */
export const encryptByDES=(message, key)=> {
	const keyHex = CryptoJS.enc.Utf8.parse(key)
	const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	})
	return encrypted.toString()
}


/**
 * 解密
 * @param {string} cipherText 密文
 * @param {string} key 密钥
 * @return {string} 解密字符串
 */
export const decryptByDES=(cipherText, key)=> {
	var keyHex = CryptoJS.enc.Utf8.parse(key)
	var decrypted = CryptoJS.DES.decrypt({
			ciphertext: CryptoJS.enc.Base64.parse(cipherText)
		},
		keyHex, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		}
	)

	return decrypted.toString(CryptoJS.enc.Utf8);
}

//获取主流程加密
export const getJwt = () => {
	// return ''
	var header = JSON.stringify({
		"typ": "JWT",
		"alg": "RS256",
		"version": "1.0.0"
	})
	let exp = dayjs().add(1440, 'minute').unix();
	var payload = JSON.stringify({
		"iss": "2002100123030134",
		"exp": exp,
	})
	let pub = jsrsasign.KEYUTIL.getKey(privateKey);
	let signature = new jsrsasign.KJUR.crypto.Signature({
		alg: "SHA256withRSA",
		prvkeypem: pub
	});
	// let beforeSign = `${base64url(header)}.${base64url(payload)}`;
	let beforeSign = `${Base64.encode(header)}.${Base64.encode(payload)}`;
	signature.updateString(beforeSign);
	let a = signature.sign();
	let sign = jsrsasign.hextob64(a);
	var reg = new RegExp('/', 'g');
	sign = sign.replace(/=+$/, '').replace(/\+/g, '-').replace(reg, '_');
	return `${beforeSign}.${sign}`;
}